package com.teamwings.ctrls.formCtrls;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.teamwings.common.aspect.annotation.FormControl;
import com.teamwings.common.constant.FormConstant;
import com.teamwings.common.vo.Result;
import com.teamwings.ctrls.FormComponent;
import com.teamwings.modules.design.vo.FormVo;
import com.teamwings.modules.page.service.IPageService;
import com.teamwings.util.FieldInject;
import lombok.Data;

import java.util.List;
import java.util.Map;

/**
 * 数据字典
 */
@Data
@FormControl(type = "oa_dict")
public class Dict extends FormComponent {

    public Dict() {
        this.type = "oa_dict";
        this.fieldDefaultLength = "200";
        this.fieldType = "VARCHAR";
    }


    /**
     * 由字典控件自己触发，获取字典数据
     * 通过postString里面的内容进行判断是获取字典，还是获取字典里面的所有项
     * @param type              触发类型，自己触发都是 CTRL_HANDLER
     * @param pageService       数据库交互service
     * @param formDesignCode    表单设计数据，这里为空
     * @param postString        自己触发，则是ajax上传的字符串，如果是由page.show[PAGE_SHOW]触发控件，则是表单所有实例数据
     * @return
     */
    @Override
    public Result<?> trigger(FormConstant.TRIGGER_TYPE type, IPageService pageService,
                             FormVo formDesignCode, Object postString) {
        String sql = "";
        JSONObject jo = JSON.parseObject(postString + "");
        // 0 get dict, 1 get dict item
        Integer listType = jo.getInteger("listType");

        // 获取字典列表
        if (listType == 0) {
            sql = "SELECT id, dict_name, dict_code FROM sys_dict ORDER BY create_time DESC";
        } else if (listType == 1) {
            String dictId = FieldInject.filter(jo.getString("id"));
            // 获取对应字典的字典项列表
            sql = "SELECT id, item_text, item_value FROM sys_dict_item WHERE dict_id = '" + dictId + "'";
        }
        List<Map> maps = pageService.executeSql(sql);
        return Result.OK("查询完成", maps);
    }
}